package com.shi.desktop.indexer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.pdmodel.PDDocumentInformation;
import org.pdfbox.util.PDFTextStripper;

public class PDFHandler implements DocumentHandler {

	public Document getDocument(InputStream is) throws DocumentHandlerException {

		PDDocument pdDoc = null;
		try {
			pdDoc = PDDocument.load(is);
		} catch (IOException e) {
			closePDDocument(pdDoc);
			throw new DocumentHandlerException("Error: Cannot load file.", e);
		}

		String docText = null;

		try {
			PDFTextStripper stripper = new PDFTextStripper();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			OutputStreamWriter writer = new OutputStreamWriter(out);
			stripper.writeText(pdDoc, writer);
			out.close();
			writer.close();
			byte[] contents = out.toByteArray();
			docText = new String(contents);
		} catch (IOException e) {
			closePDDocument(pdDoc);
			throw new DocumentHandlerException("Cannot parse PDF document", e);
		} catch (Exception e) {
			throw new DocumentHandlerException("Cannot parse PDF document", e);
		}
		

		Document doc = new Document();
		if (docText != null) {
			doc.add(new Field("content", docText, Field.Store.NO,
					Field.Index.ANALYZED));
		}

		PDDocumentInformation docInfo = pdDoc.getDocumentInformation();
		String author = docInfo.getAuthor();
		String title = docInfo.getTitle();
		String keywords = docInfo.getKeywords();
		String summary = docInfo.getSubject();
		if ((author != null) && !author.equals("")) {
			doc.add(new Field("author", author, Field.Store.YES,
					Field.Index.NOT_ANALYZED));
		}
		if ((title != null) && !title.equals("")) {
			doc.add(new Field("title", title, Field.Store.YES,
					Field.Index.ANALYZED));
		}
		if ((keywords != null) && !keywords.equals("")) {
			doc.add(new Field("keywords", keywords, Field.Store.YES,
					Field.Index.ANALYZED));
		}
		if ((summary != null) && !summary.equals("")) {
			doc.add(new Field("summary", summary, Field.Store.YES,
					Field.Index.ANALYZED));
		}
		closePDDocument(pdDoc);
		return doc;
	}

	private void closePDDocument(PDDocument pdDoc)
			throws DocumentHandlerException {
		if (pdDoc != null) {
			try {
				pdDoc.close();
			} catch (IOException e) {
				throw new DocumentHandlerException("Cannot close PDF document",
						e);
			}
		}
	}
}
